package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.BankAccountService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements BankAccountService {
    /**
     * 获取当前用户银行账号
     * @return
     */
    @Override
    public BankAccountResDTO getUserBankAccount() {
        Long currentUserId = UserContext.currentUserId();
        BankAccount bankAccount = baseMapper.selectById(currentUserId);
        if(bankAccount == null){
            return new BankAccountResDTO();
        }
        BankAccountResDTO bankAccountResDTO = BeanUtil.copyProperties(bankAccount, BankAccountResDTO.class);
        return bankAccountResDTO;
    }

    /**
     * 设置或更新银行账户
     * @param bankAccountUpsertReqDTO
     */
    @Override
    @Transactional
    public void setOrUpdateBankAccount(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {

        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        LambdaQueryWrapper<BankAccount> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(BankAccount::getId, currentUserInfo.getId())
                        .eq(BankAccount::getType, currentUserInfo.getUserType());
        baseMapper.delete(wrapper);

        BankAccount bankAccount = BeanUtil.copyProperties(bankAccountUpsertReqDTO, BankAccount.class);
        bankAccount.setId(currentUserInfo.getId());
        bankAccount.setType(currentUserInfo.getUserType());
        baseMapper.insertAndId(bankAccount);

    }
}
